namespace DotNetNuke.HttpModules
{
    using DotNetNuke.Common;
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Entities.Users;
    using DotNetNuke.Security;
    using DotNetNuke.Security.Roles;
    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Collections;
    using System.Web;
    using System.Web.Security;

    public class DNNMembershipModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication application)
        {
            application.AuthenticateRequest += new EventHandler(this.OnAuthenticateRequest);
            application.EndRequest += new EventHandler(this.OnEndRequest);
        }

        public void OnAuthenticateRequest(object s, EventArgs e)
        {
            HttpContext Context = ((HttpApplication) s).Context;
            HttpRequest Request = Context.Request;
            HttpResponse Response = Context.Response;
            if (!Request.Url.LocalPath.EndsWith("Install.aspx"))
            {
                PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings();
                string OriginalApplicationName = DotNetNuke.Common.Globals.GetApplicationName();
                if (Request.IsAuthenticated & (_portalSettings != null))
                {
                    UserInfo objUserInfo;
                    string Username;
                    MembershipUser objMembershipUser = Membership.GetUser(true);
                    if (objMembershipUser == null)
                    {
                        DotNetNuke.Common.Globals.SetApplicationName(-1);
                        objMembershipUser = Membership.GetUser();
                        DotNetNuke.Common.Globals.SetApplicationName(OriginalApplicationName);
                    }
                    if (Request.Cookies["portalaliasid"] != null)
                    {
                        FormsAuthenticationTicket PortalCookie = FormsAuthentication.Decrypt(Context.Request.Cookies["portalaliasid"].Value);
                        if (_portalSettings.PortalId != int.Parse(PortalCookie.UserData))
                        {
                            Response.Cookies["portalaliasid"].Value = null;
                            Response.Cookies["portalaliasid"].Path = "/";
                            Response.Cookies["portalaliasid"].Expires = DateTime.Now.AddYears(-30);
                            Response.Cookies["portalroles"].Value = null;
                            Response.Cookies["portalroles"].Path = "/";
                            Response.Cookies["portalroles"].Expires = DateTime.Now.AddYears(-30);
                            UserController objUsers = new UserController();
                            if (objUsers.GetUserByUsername(_portalSettings.PortalId, Context.User.Identity.Name) == null)
                            {
                                new PortalSecurity().SignOut();
                                Response.Redirect(Request.RawUrl, true);
                                return;
                            }
                        }
                    }
                    RoleController objRoleController = new RoleController();
                    UserController objUserController = new UserController();
                    int intUserId = -1;
                    string UserInfoCacheKey = objUserController.GetCacheKey(_portalSettings.PortalId, Context.User.Identity.Name);
                    if ((((DotNetNuke.Common.Globals.PerformanceSetting == DotNetNuke.Common.Globals.PerformanceSettings.HeavyCaching) && (DataCache.GetCache(UserInfoCacheKey) != null)) ? 1 : 0) != 0)
                    {
                        objUserInfo = (UserInfo) DataCache.GetCache(UserInfoCacheKey);
                    }
                    else
                    {
                        objUserInfo = objUserController.GetUserByUsername(_portalSettings.PortalId, Context.User.Identity.Name);
                        if (DotNetNuke.Common.Globals.PerformanceSetting == DotNetNuke.Common.Globals.PerformanceSettings.HeavyCaching)
                        {
                            UserInfoCacheKey = objUserController.GetCacheKey(_portalSettings.PortalId, objUserInfo.Username);
                            int intExpire = 6;
                            DataCache.SetCache(UserInfoCacheKey, objUserInfo, TimeSpan.FromMinutes((double) intExpire));
                        }
                    }
                    if (objUserInfo != null)
                    {
                        intUserId = objUserInfo.UserID;
                        Username = objUserInfo.Username;
                    }
                    else
                    {
                        new PortalSecurity().SignOut();
                        return;
                    }
                    if (((objMembershipUser == null) | objMembershipUser.IsLockedOut) | !objMembershipUser.IsApproved)
                    {
                        new PortalSecurity().SignOut();
                    }
                    else
                    {
                        if (Request.Cookies["portalroles"] == null)
                        {
                            DateTime CurrentDateTime = DateTime.Now;
                            FormsAuthenticationTicket PortalTicket = new FormsAuthenticationTicket(1, Username, CurrentDateTime, CurrentDateTime.AddHours(1.0), false, _portalSettings.PortalAlias.PortalAliasID.ToString());
                            string strPortalAliasID = FormsAuthentication.Encrypt(PortalTicket);
                            Response.Cookies["portalaliasid"].Value = strPortalAliasID;
                            Response.Cookies["portalaliasid"].Path = "/";
                            Response.Cookies["portalaliasid"].Expires = CurrentDateTime.AddMinutes(1.0);
                            string strPortalRoles = Strings.Join(objRoleController.GetPortalRolesByUser(intUserId, _portalSettings.PortalId), new string(new char[] { ';' }));
                            FormsAuthenticationTicket RolesTicket = new FormsAuthenticationTicket(1, objUserInfo.Username, CurrentDateTime, CurrentDateTime.AddHours(1.0), false, strPortalRoles);
                            string strRoles = FormsAuthentication.Encrypt(RolesTicket);
                            Response.Cookies["portalroles"].Value = strRoles;
                            Response.Cookies["portalroles"].Path = "/";
                            Response.Cookies["portalroles"].Expires = CurrentDateTime.AddMinutes(1.0);
                        }
                        if (Request.Cookies["portalroles"] != null)
                        {
                            if (Request.Cookies["portalroles"].Value != "")
                            {
                                FormsAuthenticationTicket RoleTicket = FormsAuthentication.Decrypt(Context.Request.Cookies["portalroles"].Value);
                                Context.Items.Add("UserRoles", ";" + RoleTicket.UserData + ";");
                            }
                            else
                            {
                                Context.Items.Add("UserRoles", "");
                            }
                            Context.Items.Add("UserInfo", objUserInfo);
                        }
                    }
                }
                if (((UserInfo) HttpContext.Current.Items["UserInfo"]) == null)
                {
                    Context.Items.Add("UserInfo", new UserInfo());
                }
            }
        }

        public void OnEndRequest(object s, EventArgs e)
        {
            HttpResponse Response = ((HttpApplication) s).Context.Response;
            if (Environment.Version.Major < 2)
            {
                IEnumerator refObjectHelperL0=null;
                try
                {
                    refObjectHelperL0 = Response.Cookies.GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        string cookie = Conversions.ToString(refObjectHelperL0.Current);
                        if (!Response.Cookies[cookie].Path.EndsWith(";HttpOnly"))
                        {
                            HttpCookie refObjectHelperS1 = Response.Cookies[cookie];
                            refObjectHelperS1.Path = refObjectHelperS1.Path + ";HttpOnly";
                        }
                    }
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
            }
        }

        public string ModuleName
        {
            get
            {
                return "DNNMembershipModule";
            }
        }
    }
}

